<template>
  <div class='container'>
    <el-card>
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryInfo" class="demo-form-inline" ref="ruleFormRef">
        <el-form-item label="关键字">
          <el-input v-model="queryInfo.keywords" placeholder="根据文章标题搜索"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryInfo.state" placeholder="请选择">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click=resetSearch>清除</el-button>
          <el-button type="primary" @click='getList'>搜索</el-button>
        </el-form-item>
        <el-button type="success" icon="el-icon-edit" class="iconbtn" @click='addArticle'>新增技巧
        </el-button>
      </el-form>
      <el-alert :title="`数据一共${channels.length}条`" type="info" show-icon :closable="false">
      </el-alert>
      <template>
        <el-table style="width: 100%" :data="channels">
          <el-table-column type="index" label="序号" width="80">
          </el-table-column>
          <el-table-column label="文章标题">
            <template slot-scope='scope'>
              {{scope.row.title}}<span @click='showVideodialog(scope.row)'
                v-if='scope.row.videoURL'><img src="~@/assets/video_small.png" alt="">

              </span>
            </template>
          </el-table-column>
          <el-table-column prop="visits" label="阅读数">
          </el-table-column>
          <el-table-column prop="username" label="录入人">
          </el-table-column>
          <el-table-column label="录入时间">
            <template slot-scope='scope'>
              {{scope.row.createTime | parseTimeByString}}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态">
            <template slot-scope="scope">
              {{ scope.row.state ? "已启用" : "已禁用"}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="text" @click='preview(scope.row)'>预览</el-button>
              <el-button type="text" @click='changeState(scope.row)'>
                {{!scope.row.state ? "启用" : "禁用"}}</el-button>
              <el-button type="text" :disabled='scope.row.state==1'
                @click='editDialogShowclick(scope.row)'>修改</el-button>
              <el-button type="text" :disabled='scope.row.state==1'
                @click='deleteArticle(scope.row.id)'>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 15, 20]"
            :page-size="queryInfo.pagesize" layout=" prev, pager, next,sizes, jumper" :total="total"
            background>
          </el-pagination>
        </div>
      </template>
    </el-card>
    <!-- 播放视频 -->
    <div v-if='showVideodialogVisible' class='videoShow'>
      <video v-if='showVideodialogVisible' autoplay controls :src="videoURL"></video>
      <div class="close"> <i @click='showVideodialogVisible=false' class="el-icon-error"></i></div>
    </div>

    <!-- 预览文章 -->
    <el-dialog title="预览文章" :visible.sync="previewvisible" width="50%">
      <div class="content-container">
        <h1>{{previewBody.title}}</h1>
        <div class='showInfo'>
          <span>{{previewBody.createTime |  parseTimeByString}}</span>
          <span>{{previewBody.username}}</span>
          <span> <img src="~@/assets/eye.png" alt=""></span>
          <span>{{previewBody.visits}}</span>
        </div>
        <div v-html='previewBody.articleBody' class='markdown-body content-main'></div>
      </div>

    </el-dialog>

    <!-- 修改文章 -->
    <el-dialog :title="isEditOrAdd?'修改文章':'新增文章'" :visible.sync="editdialogVisible" width="60%"
      @close='resetEditForm'>
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px"
        class="demo-ruleForm">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="articleBody">
          <quill-editor :content="editForm.articleBody" @change="onEditorChange($event)" />
        </el-form-item>
        <el-form-item label="视频地址">
          <el-input v-model="editForm.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, detail as getArticle, update as editArticle, remove as deleteArticle, add as addArticle } from '@/api/hmmm/articles'
import { parseTimeByString } from '@/filters'
export default {
  filters: {
    parseTimeByString
  },
  data () {
    return {
      queryInfo: {
        keywords: '',
        page: 1,
        pagesize: 10,
        state: null
      },
      total: 0,
      channels: [],
      previewvisible: false, // 控制预览对话框显示隐藏
      isShowVideo: false, // 控制显示视频
      showVideodialogVisible: false, // 控制视频对话框显示
      videoURL: '', // 视频地址
      previewBody: '', // 预览文章主体
      editdialogVisible: false, // 编辑文章框显示隐藏
      editForm: {
        articleBody: '',
        title: '',
        videoURL: ''
      },
      editFormRules: {
        articleBody: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ]
      },
      rowId: '', // 编辑文章需要的id
      isEditOrAdd: false// dialog显示修改还是新增
    }
  },
  methods: {
    onSubmit () {
      console.log('submit!')
    },
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.page = newPage
      this.getList()
    },
    // create获取数据
    async getList () {
      try {
        const { data: res } = await list(this.queryInfo)
        this.channels = res.items
        this.total = res.counts
      } catch (err) {
        this.$message('请求失败!')
      }
    },
    preview (row) { // 预览文章
      this.previewBody = row
      this.previewvisible = true
    },
    showVideodialog (row) { // 展示视频
      this.videoURL = row.videoURL
      this.showVideodialogVisible = true
    },
    // 有点问题
    async changeState (row) {
      // 切换禁用启用转态
      row.state = row.state === 0 ? 1 : 0
      //  try {
      //  await changeStateaaa(row.id + '/' + row.state)
      //  this.getList()
      //  this.$message.success('切换状态成功')
      //  } catch (err) {
      //  this.$message.fail('切换状态失败')
      //  }
    },
    //  resetForm () {
    //  this.$refs.ruleFormRef.resetFields()
    //  }
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    async editDialogShowclick (row) {
      // 点击显示编辑对话框
      this.isEditOrAdd = true
      this.rowId = row.id
      try {
        const { data } = await getArticle(row.id)
        this.editForm = data
      } catch (err) {
        this.$message('获取文章详情失败')
      }
      this.editdialogVisible = true
    },
    onEditorChange (data) { // 改变文章内容
      this.editForm.articleBody = data.html
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
      this.editForm = {
        articleBody: '',
        title: '',
        videoURL: ''
      }
    },
    submitEditForm () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message('标题内容必填')

        try {
          if (this.isEditOrAdd) {
            // 编辑
            await editArticle(this.rowId, this.editForm)
            this.$message.success('修改成功')
          } else {
            // 添加
            await addArticle(this.editForm)
            this.$message.success('添加成功')
          }
          this.editdialogVisible = false
        } catch (err) {
          this.$message(this.isEditOrAdd ? '编辑文章失败' : '添加文章失败')
        }
      })
    },
    async deleteArticle (id) {
      const res = await this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)
      if (res === 'cancel') return this.$message.info('取消操作')
      try {
        await deleteArticle(id)
        this.$message.success('删除成功')
        this.getList()
      } catch (err) {
        this.$message('删除失败')
      }
    },
    resetSearch () {
      this.queryInfo = {
        keywords: '',
        pagenum: 1,
        pagesize: 10,
        state: null
      }
    },
    addArticle () {
      // 新增技巧
      this.isEditOrAdd = false
      this.editdialogVisible = true
    }
  },
  created () {
    this.getList()
  }

}
</script>

<style lang='scss' scoped>
@import '../styles/github-markdown.css';
::v-deep.content-container {
  padding: 15px;
  .content-main {
    background-color: #f5f5f5;
    padding: 5px;
  }
  .ql-editor {
    height: 200px !important;
  }
  .showInfo {
    margin-bottom: 15px;
    span,
    img {
      margin-left: 10px;
      margin-bottom: 10px;
    }
    img {
      margin: 0 !important;
    }
  }
}
::v-deep.el-dialog {
  border-radius: 20px;
  z-index: 100;
}
::v-deep.el-dialog__header {
  border-radius: 20px 20px 0 0;
}
.el-card {
  margin: 10px;
}
.iconbtn {
  float: right;
}
.el-table {
  margin-top: 20px;
}
.block {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.container {
  width: 100%;
  .el-dialog__header {
    background-color: #409eff;
  }
  video {
    width: 100%;
    height: 100%;
  }
  .videoShow {
    position: absolute;
    width: 666px;
    height: 400px;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    .close {
      position: absolute;
      top: -100px;
      left: 50%;
      transform: translate(-50%);
      font-size: 60px;
      color: gray;
    }
  }
}
</style>
